package com.thinvent.recommend.manager.config;

import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.WordDictionary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(JiebaProperties.class)
public class JiebaConfig {

    private static final Logger log = LoggerFactory.getLogger(JiebaConfig.class);

    private final JiebaProperties props;

    public JiebaConfig(JiebaProperties props) {
        this.props = props;
    }

    /**
     * 分词器 Bean：加载内置模型，并在配置了 userdict 时附加自定义词典
     */
    @Bean
    public JiebaSegmenter jiebaSegmenter() throws Exception {
        JiebaSegmenter segmenter = new JiebaSegmenter();

        String custom = props.getUserdict();
        log.info("配置项 jieba.userdict = {}", custom);
        if (custom != null && !custom.trim().isEmpty()) {
            DefaultResourceLoader loader = new DefaultResourceLoader();
            Resource res = loader.getResource(custom);
            if (res.exists()) {
                Path dictPath = res.getFile().toPath();
                log.info("尝试加载自定义词典：{}", dictPath);
                WordDictionary.getInstance().loadUserDict(dictPath);
                log.info("自定义词典加载完成");
            } else {
                log.warn("自定义词典文件不存在：{}", custom);
            }
        } else {
            log.info("未配置自定义词典，跳过加载");
        }

        return segmenter;
    }

    /**
     * 停用词集合 Bean：加载后所有词都 trim + toLowerCase，跳过空行和注释
     */
    @Bean
    public Set<String> jiebaStopWords() throws Exception {
        String stop = props.getStopwords();
        log.info("配置项 jieba.stopwords = {}", stop);
        if (stop == null || stop.trim().isEmpty()) {
            log.warn("未配置停用词文件，返回空集合");
            return Collections.emptySet();
        }

        DefaultResourceLoader loader = new DefaultResourceLoader();
        Resource resource = loader.getResource(stop);
        log.info("尝试加载停用词资源：{}，exists={}", stop, resource.exists());
        if (!resource.exists()) {
            log.error("停用词文件未找到：{}，将使用空集合", stop);
            return Collections.emptySet();
        }

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
        )) {
            Set<String> stopWords = reader.lines()
                    .map(String::trim)
                    .filter(line -> !line.isEmpty())
                    .filter(line -> !line.startsWith("#"))
                    .filter(line -> !line.startsWith("//"))
                    .map(String::toLowerCase)
                    .collect(Collectors.toSet());
            log.info("停用词加载完成，共 {} 条", stopWords.size());
            return stopWords;
        }
    }
}
